import MapboxDraw from '@mapbox/mapbox-gl-draw';
import { Feature, LineString, Point, Polygon, Position } from 'geojson';

// 测距工具
class DistanceMeasureTool {
  private map: mapboxgl.Map;
  private draw: MapboxDraw;
  private markers: mapboxgl.Marker[] = []; // 距离标记
  private nodeMarkers: mapboxgl.Marker[] = []; // 节点圆点标记
  private isActive: boolean = false;

  constructor(map: mapboxgl.Map, draw: MapboxDraw) {
    // 构造函数
    this.map = map;
    this.draw = draw;

    // 绑定事件处理函数
    this.handleDrawCreate = this.handleDrawCreate.bind(this);
    this.handleDrawUpdate = this.handleDrawUpdate.bind(this);
    this.handleDrawDelete = this.handleDrawDelete.bind(this);
    this.handleDrawVertex = this.handleDrawVertex.bind(this);
  }

  /**
   * 处理绘制完成事件
   */
  private handleDrawCreate(event: { features: Feature[] }) {
    if (!this.isActive) return;

    event.features.forEach((feature) => {
      if (feature.geometry.type === 'LineString') {
        this.updateDistanceMarkers(feature as Feature<LineString>);
      }
    });
  }

  /**
   * 处理绘制更新事件
   */
  private handleDrawUpdate(event: { features: Feature[] }) {
    if (!this.isActive) return;

    event.features.forEach((feature) => {
      if (feature.geometry.type === 'LineString') {
        this.updateDistanceMarkers(feature as Feature<LineString>);
      }
    });
  }

  /**
   * 处理绘制删除事件
   */
  private handleDrawDelete() {
    if (!this.isActive) return;
    this.clearMarkers();
  }

  /**
   * 处理绘制顶点事件
   */
  private handleDrawVertex(event: { features: Feature[] }) {
    if (!this.isActive) return;

    event.features.forEach((feature) => {
      if (feature.geometry.type === 'LineString') {
        this.updateDistanceMarkers(feature as Feature<LineString>);
      }
    });
  }

  /**
   * 更新距离标记和节点圆点
   */
  private updateDistanceMarkers(feature: Feature<LineString>) {
    // 清除旧标记
    this.clearMarkers();

    const coordinates = feature.geometry.coordinates;
    let totalDistance = 0;

    // 添加节点圆点和距离标记
    for (let i = 0; i < coordinates.length; i++) {
      const point = coordinates[i];

      // 添加节点圆点
      this.addNodeMarker(point);

      // 如果是起点，添加起点提示
      if (i === 0) {
        this.addStartMarker(point);
      }

      // 如果是最后一个点，不计算距离
      if (i === 0) continue;

      // 计算当前线段的距离
      const prevPoint = coordinates[i - 1];
      const segmentDistance = this.calculateDistance(prevPoint, point);
      totalDistance += segmentDistance;

      // 在节点之间添加距离标记
      this.addMarker(point, `距离: ${(totalDistance * 0.001).toFixed(2)} km`);
    }
  }

  /**
   * 计算两点之间的距离
   */
  private calculateDistance(start: Position, end: Position): number {
    const startLngLat = new mapboxgl.LngLat(start[0], start[1]);
    const endLngLat = new mapboxgl.LngLat(end[0], end[1]);
    return startLngLat.distanceTo(endLngLat);
  }

  /**
   * 添加距离标记
   */
  private addMarker(position: Position, text: string) {
    const el = document.createElement('div');
    el.className = 'distance-marker';
    el.textContent = text;

    const marker = new mapboxgl.Marker(el)
      .setLngLat([position[0], position[1]])
      .addTo(this.map);

    this.markers.push(marker);
  }

  /**
   * 添加节点圆点
   */
  private addNodeMarker(position: Position) {
    const el = document.createElement('div');
    el.className = 'node-marker';

    const marker = new mapboxgl.Marker(el)
      .setLngLat([position[0], position[1]])
      .addTo(this.map);

    this.nodeMarkers.push(marker);
  }

  /**
   * 添加起点提示
   */
  private addStartMarker(position: Position) {
    const el = document.createElement('div');
    el.className = 'start-marker';
    el.textContent = '起点';

    const marker = new mapboxgl.Marker(el)
      .setLngLat([position[0], position[1]])
      .setOffset([0, -20]) // 偏移量，避免与点重叠
      .addTo(this.map);

    this.markers.push(marker);
  }

  /**
   * 清除所有标记
   */
  private clearMarkers() {
    // 清除距离标记
    this.markers.forEach((marker) => marker.remove());
    this.markers = [];

    // 清除节点圆点标记
    this.nodeMarkers.forEach((marker) => marker.remove());
    this.nodeMarkers = [];
  }

  /**
   * 清空绘制的线段和点
   */
  private clearDrawings() {
    const features = this.draw.getAll();
    if (features.features.length > 0) {
      features.features.forEach((feature) => {
        this.draw.delete(feature.id); // 删除绘制的线段和点
      });
    }
  }

  /**
   * 清理资源和事件监听器
   */
  private cleanup() {
    // 清除标记
    this.clearMarkers();

    // 清空绘制的线段和点
    this.clearDrawings();

    // 移除事件监听器
    this.map.off('draw.create', this.handleDrawCreate);
    this.map.off('draw.update', this.handleDrawUpdate);
    this.map.off('draw.delete', this.handleDrawDelete);
    this.map.off('draw.vertex', this.handleDrawVertex);

    // 重置状态
    this.isActive = false;
  }

  /**
   * 启动测距工具
   */
  public start() {
    if (this.isActive) return;

    // 确保地图和绘制控件已初始化
    if (!this.map || !this.draw) {
      console.error('Map或者画布已经初始化了！');
      return;
    }

    // 添加事件监听器
    this.map.on('draw.create', this.handleDrawCreate);
    this.map.on('draw.update', this.handleDrawUpdate);
    this.map.on('draw.delete', this.handleDrawDelete);
    this.map.on('draw.vertex', this.handleDrawVertex); // 监听顶点事件

    // 检查是否有已绘制的线段
    const features = this.draw.getAll();
    if (features.features.length > 0) {
      // 如果有已绘制的线段，进入编辑模式
      const featureId = features.features[0].id;
      this.draw.changeMode('direct_select', { featureId });
    } else {
      // 如果没有已绘制的线段，进入绘制模式
      this.draw.changeMode('draw_line_string');
    }

    // 设置状态为激活
    this.isActive = true;
  }

  /**
   * 停止测距工具
   */
  public stop() {
    if (!this.isActive) return;

    // 确保地图和绘制控件已初始化
    if (!this.map || !this.draw) {
      console.error('地图或者画布未初始化！.');
      return;
    }

    // 退出绘制模式
    this.draw.changeMode('simple_select');

    // 清理资源和事件监听器
    this.cleanup();
  }
}

import { polygon, area } from '@turf/turf'; // 使用 Turf.js 计算面积

// 面绘制工具
class AreaMeasureTool {
  private map: mapboxgl.Map;
  private draw: MapboxDraw;
  private markers: mapboxgl.Marker[] = []; // 面积标记
  private isActive: boolean = false;

  constructor(map: mapboxgl.Map, draw: MapboxDraw) {
    this.map = map;
    this.draw = draw;

    // 绑定事件处理函数
    this.handleDrawCreate = this.handleDrawCreate.bind(this);
    this.handleDrawUpdate = this.handleDrawUpdate.bind(this);
    this.handleDrawDelete = this.handleDrawDelete.bind(this);
    this.handleDrawVertex = this.handleDrawVertex.bind(this);
  }

  /**
   * 处理绘制完成事件
   */
  private handleDrawCreate(event: { features: Feature[] }) {
    if (!this.isActive) return;

    event.features.forEach((feature) => {
      if (feature.geometry.type === 'Polygon') {
        this.updateAreaMarker(feature as Feature<Polygon>);
      }
    });
  }

  /**
   * 处理绘制更新事件
   */
  private handleDrawUpdate(event: { features: Feature[] }) {
    if (!this.isActive) return;

    event.features.forEach((feature) => {
      if (feature.geometry.type === 'Polygon') {
        this.updateAreaMarker(feature as Feature<Polygon>);
      }
    });
  }

  /**
   * 处理绘制删除事件
   */
  private handleDrawDelete() {
    if (!this.isActive) return;
    this.clearMarkers();
  }

  /**
   * 处理绘制顶点事件
   */
  private handleDrawVertex(event: { features: Feature[] }) {
    if (!this.isActive) return;

    event.features.forEach((feature) => {
      if (feature.geometry.type === 'Polygon') {
        this.updateAreaMarker(feature as Feature<Polygon>);
      }
    });
  }

  /**
   * 更新面积标记
   */
  private updateAreaMarker(feature: Feature<Polygon>) {
    // 清除旧标记
    this.clearMarkers();

    // 计算面的面积
    let polygonArea = this.calculateArea(feature);

    // 获取面的中心点
    const center = this.getPolygonCenter(feature);

    // 在面的中心点添加面积标记
    // 转为万平方公里
    polygonArea = polygonArea / 10000000000;
    this.addMarker(center, `面积: ${polygonArea.toFixed(4)} 万 km²`);
  }

  /**
   * 计算面的面积
   */
  private calculateArea(feature: Feature<Polygon>): number {
    const turfPolygon = polygon(feature.geometry.coordinates);
    return area(turfPolygon); // 使用 Turf.js 计算面积
  }

  /**
   * 获取面的中心点
   */
  private getPolygonCenter(feature: Feature<Polygon>): Position {
    const coordinates = feature.geometry.coordinates[0]; // 获取面的外环坐标
    let sumLng = 0;
    let sumLat = 0;

    // 计算所有顶点的平均值
    coordinates.forEach((point) => {
      sumLng += point[0];
      sumLat += point[1];
    });

    const centerLng = sumLng / coordinates.length;
    const centerLat = sumLat / coordinates.length;

    return [centerLng, centerLat];
  }

  /**
   * 添加面积标记
   */
  private addMarker(position: Position, text: string) {
    const el = document.createElement('div');
    el.className = 'area-marker';
    el.textContent = text;

    const marker = new mapboxgl.Marker(el)
      .setLngLat([position[0], position[1]])
      .addTo(this.map);

    this.markers.push(marker);
  }

  /**
   * 清除所有标记
   */
  private clearMarkers() {
    this.markers.forEach((marker) => marker.remove());
    this.markers = [];
  }

  /**
   * 清空绘制的面
   */
  private clearDrawings() {
    const features = this.draw.getAll();
    if (features.features.length > 0) {
      features.features.forEach((feature: { id: any; }) => {
        this.draw.delete(feature.id); // 删除绘制的面
      });
    }
  }

  /**
   * 清理资源和事件监听器
   */
  private cleanup() {
    // 清除标记
    this.clearMarkers();

    // 清空绘制的面
    this.clearDrawings();

    // 移除事件监听器
    this.map.off('draw.create', this.handleDrawCreate);
    this.map.off('draw.update', this.handleDrawUpdate);
    this.map.off('draw.delete', this.handleDrawDelete);
    this.map.off('draw.vertex', this.handleDrawVertex);

    // 重置状态
    this.isActive = false;
  }

  /**
   * 启动面绘制工具
   */
  public start() {
    if (this.isActive) return;

    // 确保地图和绘制控件已初始化
    if (!this.map || !this.draw) {
      console.error('地图或者画布未初始化！.');
      return;
    }

    // 添加事件监听器
    this.map.on('draw.create', this.handleDrawCreate);
    this.map.on('draw.update', this.handleDrawUpdate);
    this.map.on('draw.delete', this.handleDrawDelete);
    this.map.on('draw.vertex', this.handleDrawVertex); // 监听顶点事件

    // 检查是否有已绘制的面
    const features = this.draw.getAll();
    if (features.features.length > 0) {
      // 如果有已绘制的面，进入编辑模式
      const featureId = features.features[0].id;
      this.draw.changeMode('direct_select', { featureId });
    } else {
      // 如果没有已绘制的面，进入绘制模式
      this.draw.changeMode('draw_polygon');
    }

    // 设置状态为激活
    this.isActive = true;
  }

  /**
   * 停止面绘制工具
   */
  public stop() {
    if (!this.isActive) return;

    // 确保地图和绘制控件已初始化
    if (!this.map || !this.draw) {
      console.error('地图或者画布未初始化！.');
      return;
    }

    // 退出绘制模式
    this.draw.changeMode('simple_select');

    // 清理资源和事件监听器
    this.cleanup();
  }
}


// 绘制点工具
class PointMarkerTool {
  private map: mapboxgl.Map;
  private draw: MapboxDraw;
  private markers: mapboxgl.Marker[] = []; // 存储标记点
  private isActive: boolean = false;
  private pointCounter: number = 1; // 标记点序号计数器
  private mouseType: number = 0; // 0:鼠标左键 1:鼠标右键

  constructor(map: mapboxgl.Map, draw: MapboxDraw) {
    this.map = map;
    this.draw = draw;

    // 绑定事件处理函数
    this.handleDrawCreate = this.handleDrawCreate.bind(this);
    this.handleDrawDelete = this.handleDrawDelete.bind(this);
    this.handleMapMouseDown = this.handleMapMouseDown.bind(this);
  }

  /**
   * 处理绘制完成事件
   */
  private handleDrawCreate(event: { features: Feature[] }) {
    if (!this.isActive) return;

    event.features.forEach((feature) => {
      if (feature.geometry.type === 'Point') {
        this.addPointMarker(feature as Feature<Point>);
      }
    });

    // 强制重新进入绘制模式
    setTimeout(() => {
      this.draw.changeMode('draw_point');
    }, 0);
  }

  /**
   * 处理绘制删除事件
   */
  private handleDrawDelete() {
    if (!this.isActive) return;
    this.clearMarkers();
    this.pointCounter = 1; // 重置计数器
  }

  /**
   * 处理地图鼠标按下事件
   */
  private handleMapMouseDown(event: mapboxgl.MapMouseEvent) {
    if (!this.isActive) return;

    // 检查是否是右键点击
    if (event.originalEvent.button === 2) {
      // 右键点击，切换到 simple_select 模式
      this.draw.changeMode('simple_select');
      event.originalEvent.preventDefault(); // 阻止右键默认行为
      return;
    }
  }

  /**
   * 添加标记点
   */
  private addPointMarker(feature: Feature<Point>) {
    // 获取点的坐标
    const coordinates = feature.geometry.coordinates;

    // 在点的位置添加标记
    const label = `序号: ${this.pointCounter}, 坐标: ${coordinates[0].toFixed(4)}, ${coordinates[1].toFixed(4)}`;
    this.addMarker(coordinates, label);

    // 增加计数器
    this.pointCounter++;
  }

  /**
   * 添加标记点
   */
  private addMarker(position: Position, text: string) {
    // 创建点的容器
    const el = document.createElement('div');
    el.className = 'point-marker';

    // 创建点的圆
    const pointCircle = document.createElement('div');
    pointCircle.className = 'point-circle';
    el.appendChild(pointCircle);

    // 创建 label
    const label = document.createElement('div');
    label.className = 'point-label';
    label.textContent = text;
    el.appendChild(label);

    // 设置 label 样式
    label.style.position = 'absolute';
    label.style.transform = 'translate(-50%, -150%)'; // 向上偏移
    label.style.backgroundColor = 'white';
    label.style.padding = '4px 8px';
    label.style.borderRadius = '4px';
    label.style.border = '1px solid #ccc';
    label.style.fontSize = '12px';
    label.style.whiteSpace = 'nowrap';
    label.style.zIndex = '1'; // 确保 label 在点的上方

    // 设置点的样式
    pointCircle.style.width = '16px'; // 增大点的圆的大小
    pointCircle.style.height = '16px';
    pointCircle.style.backgroundColor = '#ff0000';
    pointCircle.style.borderRadius = '50%';
    pointCircle.style.border = '2px solid white';

    const marker = new mapboxgl.Marker({
      element: el,
      offset: [0, 0], // 不需要额外的偏移
    })
      .setLngLat([position[0], position[1]])
      .addTo(this.map);

    this.markers.push(marker);
  }

  /**
   * 清除所有标记点
   */
  private clearMarkers() {
    this.markers.forEach((marker) => marker.remove());
    this.markers = [];
  }

  /**
   * 清空绘制的点
   */
  private clearDrawings() {
    const features = this.draw.getAll();
    if (features.features.length > 0) {
      features.features.forEach((feature: { id: any }) => {
        this.draw.delete(feature.id); // 删除绘制的点
      });
    }
  }

  /**
   * 清理资源和事件监听器
   */
  private cleanup() {
    // 清除标记点
    this.clearMarkers();

    // 清空绘制的点
    this.clearDrawings();

    // 移除事件监听器
    this.map.off('draw.create', this.handleDrawCreate);
    this.map.off('draw.delete', this.handleDrawDelete);
    this.map.off('mousedown', this.handleMapMouseDown);

    // 重置状态
    this.isActive = false;
    this.pointCounter = 1; // 重置计数器
  }

  /**
   * 启动标记点绘制工具
   */
  public start() {
    if (this.isActive) return;

    // 确保地图和绘制控件已初始化
    if (!this.map || !this.draw) {
      console.error('Map or Draw control is not initialized.');
      return;
    }

    // 添加事件监听器
    this.map.on('draw.create', this.handleDrawCreate);
    this.map.on('draw.delete', this.handleDrawDelete);
    this.map.on('mousedown', this.handleMapMouseDown); // 监听地图鼠标按下事件

    // 进入点绘制模式
    this.draw.changeMode('draw_point');

    // 设置状态为激活
    this.isActive = true;
  }

  /**
   * 停止标记点绘制工具
   */
  public stop() {
    if (!this.isActive) return;

    // 确保地图和绘制控件已初始化
    if (!this.map || !this.draw) {
      console.error('Map or Draw control is not initialized.');
      return;
    }

    // 退出绘制模式
    this.draw.changeMode('simple_select');

    // 清理资源和事件监听器
    this.cleanup();
  }
}

import { showWarningMessage } from "../message/index";
// 绘制两点连线
class LineDrawingTool {
  private map: mapboxgl.Map;
  private markers: mapboxgl.Marker[] = []; // 存储标记点
  private line: mapboxgl.Layer | null = null; // 存储连线
  private isActive: boolean = false;
  private startPoint: mapboxgl.LngLat | null = null; // 起点
  private endPoint: mapboxgl.LngLat | null = null; // 终点
  private tempLine: mapboxgl.Layer | null = null; // 临时连线
  private onLineDrawn: ((start: mapboxgl.LngLat, end: mapboxgl.LngLat) => void) | null = null; // 回调函数

  // 绘制范围
  private drawRange = [[121.38, 40.5], [131.19, 40.5], [131.19, 46.19], [121.38, 46.19]];
  constructor(map: mapboxgl.Map) {
    this.map = map;
    this.targetLayerIds = ['radarPng', 'radarTif']; // 需要判断的目标图层 ID 列表
    // 绑定事件处理函数
    this.handleMapClick = this.handleMapClick.bind(this);
    this.handleMapMouseMove = this.handleMapMouseMove.bind(this);
  }

  /**
   * 处理地图点击事件
   */
  private handleMapClick(event: mapboxgl.MapMouseEvent) {
    if (!this.isActive) return;

    // 确保地图加载完成
    if (!this.map.isStyleLoaded()) {
      console.error('地图样式未加载完成');
      return;
    }
    if (this.map.getLayer('radarPng') || this.map.getLayer('radarTif')) {
      if (this.isPointInPolygon([event.lngLat.lng, event.lngLat.lat], this.drawRange)) {
        const lngLat = event.lngLat;
        if (!this.startPoint) {
          // 设置起点
          this.startPoint = lngLat;
          this.addMarker(lngLat, '起点');
        } else if (!this.endPoint) {
          // 设置终点
          this.endPoint = lngLat;
          this.addMarker(lngLat, '终点');
          this.drawLine(this.startPoint, this.endPoint);
          this.removeTempLine();

          // 触发回调函数，返回起点和终点坐标
          if (this.onLineDrawn && this.startPoint && this.endPoint) {
            this.onLineDrawn(this.startPoint, this.endPoint);
          }

          // 重置起点和终点，以便下一次绘制
          this.startPoint = null;
          this.endPoint = null;
          this.close(); // 绘制完成后关闭工具
        }


      } else {
        showWarningMessage("请在正确雷达范围中标点!")

      }

    } else {
      showWarningMessage("请在正确雷达范围中标点!")
    }
  }

  /**
 * 判断一个点是否在多边形范围内
 * @param point 要判断的点，格式为 [经度, 纬度]
 * @param polygon 多边形范围，格式为 [[经度, 纬度], [经度, 纬度], ...]
 * @returns 如果点在多边形内返回 true，否则返回 false
 */
  private isPointInPolygon(point: [number, number], polygon: any): boolean {
    const [x, y] = point;
    let inside = false;

    // 遍历多边形的每一条边
    for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
      const [xi, yi] = polygon[i];
      const [xj, yj] = polygon[j];

      // 判断点是否在边的范围内
      const intersect =
        yi > y !== yj > y && // 点的 y 坐标在边的 y 坐标范围内
        x < ((xj - xi) * (y - yi)) / (yj - yi) + xi; // 点的 x 坐标在边的左侧

      if (intersect) {
        inside = !inside; // 切换状态
      }
    }

    return inside;
  }

  /**
   * 处理地图鼠标移动事件
   */
  private handleMapMouseMove(event: mapboxgl.MapMouseEvent) {
    if (!this.isActive || !this.startPoint || this.endPoint) return;

    const lngLat = event.lngLat;
    this.updateTempLine(this.startPoint, lngLat);
  }

  /**
   * 添加标记点
   */
  private addMarker(position: mapboxgl.LngLat, text: string) {
    const el = document.createElement('div');
    el.className = 'point-marker';

    const pointCircle = document.createElement('div');
    pointCircle.className = 'point-circle';
    el.appendChild(pointCircle);

    const label = document.createElement('div');
    label.className = 'point-label';
    label.textContent = text;
    el.appendChild(label);

    label.style.position = 'absolute';
    label.style.transform = 'translate(-50%, -150%)';
    label.style.backgroundColor = 'white';
    label.style.padding = '4px 8px';
    label.style.borderRadius = '4px';
    label.style.border = '1px solid #ccc';
    label.style.fontSize = '12px';
    label.style.whiteSpace = 'nowrap';
    label.style.zIndex = '1';

    pointCircle.style.width = '16px';
    pointCircle.style.height = '16px';
    pointCircle.style.backgroundColor = '#ff0000';
    pointCircle.style.borderRadius = '50%';
    pointCircle.style.border = '2px solid white';

    const marker = new mapboxgl.Marker({
      element: el,
      offset: [0, 0],
    })
      .setLngLat([position.lng, position.lat])
      .addTo(this.map);

    this.markers.push(marker);
  }

  /**
   * 绘制连线
   */
  private drawLine(start: mapboxgl.LngLat, end: mapboxgl.LngLat) {
    if (this.line) {
      this.map.removeLayer('line');
      this.map.removeSource('line');
    }

    this.map.addSource('line', {
      type: 'geojson',
      data: {
        type: 'Feature',
        geometry: {
          type: 'LineString',
          coordinates: [
            [start.lng, start.lat],
            [end.lng, end.lat],
          ],
        },
      },
    });

    this.map.addLayer({
      id: 'line',
      type: 'line',
      source: 'line',
      layout: {},
      paint: {
        'line-color': '#ff0000',
        'line-width': 2,
      },
    });

    this.line = this.map.getLayer('line');
  }

  /**
   * 更新临时连线
   */
  private updateTempLine(start: mapboxgl.LngLat, end: mapboxgl.LngLat) {
    if (this.tempLine) {
      this.map.removeLayer('temp-line');
      this.map.removeSource('temp-line');
    }

    this.map.addSource('temp-line', {
      type: 'geojson',
      data: {
        type: 'Feature',
        geometry: {
          type: 'LineString',
          coordinates: [
            [start.lng, start.lat],
            [end.lng, end.lat],
          ],
        },
      },
    });

    this.map.addLayer({
      id: 'temp-line',
      type: 'line',
      source: 'temp-line',
      layout: {},
      paint: {
        'line-color': '#00ff00',
        'line-width': 2,
      },
    });

    this.tempLine = this.map.getLayer('temp-line');
  }

  /**
   * 移除临时连线
   */
  private removeTempLine() {
    if (this.tempLine) {
      this.map.removeLayer('temp-line');
      this.map.removeSource('temp-line');
      this.tempLine = null;
    }
  }

  /**
   * 清除所有标记点和连线
   */
  private clearMarkersAndLine() {
    this.markers.forEach((marker) => marker.remove());
    this.markers = [];

    if (this.line) {
      this.map.removeLayer('line');
      this.map.removeSource('line');
      this.line = null;
    }

    this.removeTempLine();
  }

  /**
   * 清理资源和事件监听器
   */
  private cleanup() {
    this.clearMarkersAndLine();
    this.close()
  }

  /** 
   * 关闭绘制
   */
  public close() {
    this.map.off('click', this.handleMapClick);
    this.map.off('mousemove', this.handleMapMouseMove);
    this.isActive = false;
    this.startPoint = null;
    this.endPoint = null;
  }

  /**
   * 启动连线绘制工具
   * @param onLineDrawn 每次完成两点连线时的回调函数
   */
  public start(onLineDrawn: (start: mapboxgl.LngLat, end: mapboxgl.LngLat) => void) {
    if (this.isActive) return;

    if (!this.map) {
      console.error('Map is not initialized.');
      return;
    }

    // 设置回调函数
    this.onLineDrawn = onLineDrawn;

    // 重置起点和终点
    this.startPoint = null;
    this.endPoint = null;

    this.map.on('click', this.handleMapClick);
    this.map.on('mousemove', this.handleMapMouseMove);

    this.isActive = true;
  }

  /**
   * 停止连线绘制工具
   */
  public stop() {
    // if (!this.isActive) return;

    if (!this.map) {
      console.error('Map is not initialized.');
      return;
    }

    this.cleanup();
  }
}

export { DistanceMeasureTool, AreaMeasureTool, PointMarkerTool, LineDrawingTool };